/**
 * 
 */
package cu.ds.logicalsync.fytasrealm.communication.model;

import net.jxta.document.AdvertisementFactory;
import net.jxta.id.IDFactory;
import net.jxta.peer.PeerID;
import net.jxta.pipe.PipeID;
import net.jxta.pipe.PipeService;
import net.jxta.protocol.PipeAdvertisement;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;

import cu.ds.logicalsync.fytasrealm.communication.JxtaConnection;

/**
 * Peer represent an individual client in the Network
 * 
 * @author r.vashira
 */
public class PeerInfo {
	/** Constants **/
	public static final String PEER_PIPE = "PEER_PIPE";
	
	/*** Member Variables ***/
	private PeerID id;
	private String name;
	private PipeAdvertisement address = null;
	
	/*** Properties ***/
	public PeerID getId() {
		return id;
	}

	public void setId(PeerID id) {
		this.id = id;
	}
	
	public String getName() {
		return name;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	/**
	 * Get connection address for this Peer in form of PipeAdvertisement for 1-1 communication
	 * @return
	 */
	public PipeAdvertisement getAddress() {
		// Initialize address of this Peer for pipelining  
		if(address == null) {
			// using PeerID as a seed to generate unique PipeID 
			PipeID pipeID = IDFactory.newPipeID(JxtaConnection.getInstance(getName()).getMyPeerGroupID(),
					getId().toString().getBytes());
			PipeAdvertisement advertisement = (PipeAdvertisement) 
				AdvertisementFactory.newAdvertisement(PipeAdvertisement.getAdvertisementType());
			advertisement.setPipeID(pipeID);
			advertisement.setType(PipeService.UnicastType);
			advertisement.setName(PEER_PIPE);
			
			address = advertisement;
		}
		return address;
	}
	
	/**
	 * Default Constructor
	 * @param name
	 */
	public PeerInfo(String name) {
		super();
		
		this.name = name;
	}
	
	@Override
	public boolean equals(Object obj) {
		if (obj == null)
            return false;
        if (obj == this)
            return true;
        if (obj.getClass() != getClass())
            return false;

        PeerInfo rhs = (PeerInfo) obj;
        
        // if deriving: appendSuper(super.equals(obj)).
        return new EqualsBuilder().
            append(id, rhs.getId()).
            append(name, rhs.getName()).
            isEquals();
	}
	
	@Override
	public int hashCode() {
		// two randomly chosen prime numbers
		// if deriving: appendSuper(super.hashCode()).
		return new HashCodeBuilder(17, 31).
			append(id).
			append(name).
			toHashCode();
	}
	
	@Override
	public String toString() {
		return "PeerName: " + name + ", PeerID: " + id;
	}
	
}
